<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
           <a-col :span="24" v-show="false">
            <a-form-model-item label="数据类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="busKeys">
             
                 <a-input   disabled v-model="model.busKeys" placeholder="请输入数据对象"  ></a-input>
            </a-form-model-item>
          </a-col> 
          <a-col :span="24">
            <a-form-model-item label="数据类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="busField">
               <a-select placeholder="请选择权限类型" v-model="model.busField" @change="handleTypeChange">
                <a-select-option :value="item.code" v-for="item in dict.orderList0" :key="item.code">{{item.name}}</a-select-option>
              </a-select> 
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-show="!!model.busField">
            <a-form-model-item label="数据对象" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="busType">
                <a-input :key="model.busField" ref="busTypeRef" v-if="model.busField == 10" disabled v-model="model.busTypeName" placeholder="请输入数据对象"  ></a-input>
                <std-select-depart :key="model.busField" @getName="getBusFieldName" ref="busTypeRef" name="组织架构组" 
                url="/dataGroup/groupTree" 
                :queryParam='{busField:"标准样",busKey:"dep"}' 
                v-else-if="model.busField == 20" v-model="model.busType" :multi="false" :replaceFields="{children:'children', title:'title', key:'key', value: 'key' }"></std-select-depart>
                <std-select-depart :key="model.busField" @getName="getBusFieldName"  ref="busTypeRef" v-else-if="model.busField == 30" v-model="model.busType" :multi="false" :replaceFields="{children:'children', title:'title', key:'id', value: 'id' }"></std-select-depart>
                <std-select-depart :key="model.busField"  @getName="getBusFieldName" ref="busTypeRef" name="用户组"
                url="/dataGroup/groupTree" 
                :queryParam='{busField:"标准样",busKey:"user"}' 
                  v-else-if="model.busField == 40" v-model="model.busType" :multi="false" :replaceFields="{children:'children', title:'title', key:'key', value: 'key' }"></std-select-depart>
                <StdSelectMultiUser :key="model.busField" @getName="getBusFieldName" ref="busTypeRef" v-else-if="model.busField == 50" v-model="model.busType" :multiple="false"></StdSelectMultiUser>

            </a-form-model-item>
          </a-col>
        <a-col :span="24">
            <a-form-model-item label="权限" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="permissionValue">
                  <std-select-depart ref="permissionRef" @back="savePermission" @getName="getPermiName" customReturnField="code" 
                  customReturnTitleField="name" :backInfo="{value:'permissionValue',text:'permissionName'}" 
                  v-model="model.permissionValue" name="标准样权限" 
                  url="/manage/codeInfo/list" :queryParam='{type:"标准样数据权限",pageSize:-1,isdel: 0,column:"code",order:"Asc"}' 
                  :multi="true" :replaceFields="{children:'children', title:'name', key:'code', value: 'code' }">
                  </std-select-depart>
                  
            </a-form-model-item>
          </a-col>
         <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea  auto-size v-model="model.remark" placeholder="请输入备注" :max-length="255" ></a-textarea>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import {codeInfoList,codeInfoByTypeAndParent} from '@/api/codeInfo'
  export default {
    name: 'StdSampleScopeForm',
    components: {
      stdSelectDepart:()=> import('@/views/library/stdSample/StdSelectDepart'),
      StdSelectMultiUser:()=> import('@/views/library/stdSample/StdSelectMultiUser'),
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      dataSource:{
        type:Array,
        default:()=>{return []},
        required: false,
      }
    },
    data () {
      return {
        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           busKeys: [
              { required: true, message: '请输入目录ID!'},
           ],
           busField: [
              { required: true, message: '请选择数据类型!'},
           ],
           busType: [
              { required: true, message: '请选择数据对象!'},
           ],
            permissionValue:[
              { required: true, message: '请选择权限!'},
            ],
           
        },
        url: {
          add: "/stdSampleScope/add",
          edit: "/stdSampleScope/edit",
          saveScope: '/stdSampleScope/saveScope',
          queryById: "/stdSampleScope/queryById"
        },
        dict:{
          orderList0:[],
          orderList1:[],
        },
        customParam:{},
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.initDictConfig()

      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      handleTypeChange(val){
        let busType = ''
        let busTypeName = ''
        let busFieldName = ''
        let codeInfo = !!this.dict.orderList0.find(item => {return item.code == val})  ? this.dict.orderList0.find(item => {return item.code == val}):{}
        busFieldName = codeInfo.name
        switch (val) {
          case '10':
            busType = codeInfo.code
            busTypeName = codeInfo.name
            break;
          default:
            break;
        }

        this.$set(this.model,'busType',busType)
        this.$set(this.model,'busTypeName',busTypeName)
        this.$set(this.model,'busFieldName',busFieldName)
      },
      getBusFieldName(name){
         this.$set(this.model,'busTypeName',name)
      },
       initDictConfig(){
         const list = ['标准样数据权限分类','标准样数据权限']
      list.forEach((item, index)=>{
        codeInfoList({type:item,pageSize:-1,isdel: 0,column:"code",order:"Asc"}).then((res) => {
          if (res.code == 200) {
            this.dict['orderList'+ index] = res.result.records
           
          } else {
            this.$message.warning('操作异常:' + res.message)
          }
        })
      })  
      },
      add () {
        this.modelDefault = JSON.parse(JSON.stringify(this.model));
        this.edit(this.modelDefault);
      },
      edit (record) {
        
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpurl=this.url.saveScope;
            method = 'post';
            if(this.customParam.batchFlag ){
               if(this.model.add){
                
                let one = this.dataSource.find(item=>{
                    return item.busField == this.model.busField && item.busType == this.model.busType
                  })
                  if(!!one){
                    that.$message.success('数据已存在新增失败!');
                    that.confirmLoading = false;
                    return
                  }
              }
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok',this.model);
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      savePermission(samplePermissions){
        this.$set(this.model,'samplePermissions',samplePermissions)
        
      },
      getPermiName(name){
        this.$set(this.model,'permissionName',name)
      },
    }
  }
</script>